
package com.jinbo.footmessage.baiduMap;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.SDKInitializer;
import com.jinbo.footmessage.BaseActivity;
import com.jinbo.footmessage.MyApplication;
import com.jinbo.footmessage.MyBaiduListenerHelper;
import com.jinbo.footmessage.R;
import com.jinbo.footmessage.utils.BaiduMapUtils;
import com.jinbo.footmessage.utils.LatLngBean;
import com.jinbo.footmessage.utils.LocalPreferencesHelper;
import com.jinbo.footmessage.view.CrossEditText;
import com.jinbo.footmessage.view.TitleBarView;;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

/*
百度地图有一个特点，就是当我们点击某一个选项时，如果与之前的位置不同，那么他的会引起地图状态的改变onMapStatusChangeStart，
onMapStatusChange，onMapStatusChangeFinish这三种变化
点击某一个选项时，如果与之前的位置相同。第一次时，那么他的只会引起地图状态的改变onMapStatusChangeStart。其他变化都没有
如果再点击相同，及第二次时，就不会引起地图状态的改变（onMapStatusChangeStart onMapStatusChange，onMapStatusChangeFinish
都没有。。级第二次以后都是没有的。
多次点击定位，还有点击同一选择列表都要考虑上面的情况。更要注意，有些百度提供的关联位置，是同一个地点，会放在不同的选项。比如华南
师范大学外国语言学院，还有政治学院是不同的选项，但他们地点是相同的，这时切换起地图状态的改变就是不一样的。
 */
public class SelectAddressActivity extends BaseActivity implements MyBaiduListenerHelper.OnLocationListener
        , MyBaiduListenerHelper.OnGeoListener, MyBaiduListenerHelper.OnMapChangeListener, View.OnClickListener
        , MyBaiduListenerHelper.OnGetSuggestionListener {
    public static final String ADDRESS = "ADDRESS";
    public static final String LAT = "LAT";
    public static final String LNG = "LNG";
   // public static final String ID = "ID";

    private Point poi;//new Point(0,0); 地图中间点
    private boolean isChanged = true;//反编码是否刷新下面的列表,如当当用户点击下面的列表选项就不用刷新了
    private Animation anim1;//大头针跳转动画1
    private Animation anim2;//大头针跳转动画1
    private ListView list;//位置选择装地图下面的列表。

    /*
     下面的参数，用户点击下面的列表选项相关。就是考虑上面所说的情况
     */
    private double lastLat;
    private double lastLng;
    private int time = 0;
    private boolean isSameClick = false;

    private LinearLayout listLayout;//选择地址列表的布局，布局包括上面的list,
    // 还有包括一个"*如果您不在项目附近，可搜索地址进行添加或手动输入"
    private LinearLayout bar;//加载的布局
    private View mFailLoad;//加载失败
    private View mBarLoad;//正在加载布局


    private BaiduMapUtils mMaputil;//封装百度地图类
    //注意到定位时，地图状态不一定改变（点击一次定位，再点击就不是这种情况，就是我最上面说的），原来我是在地图改变开始刷新圈圈。地图改变结束调用反编码，然后刷新下面地址选择列表
    //注意到这种情况后，就需要对当时定位操作时进行特别操作（在定位回调里调用反编码，然后在回调里判断转圈圈）
    //注意有时定位没状态改变没有（1）start； 或（2）只有START；有时（3）SATART ,CHANGE ,FINISH都有

    private ImageView ima;//大头针
    private int firstLoc = 1;//是否为第一次进来，当为第一次是进来，在显示大头针后弹出我的位置提示框，当移动地图或者点击下面
    //列表时，提示框结束

    private int isLoc = 0;//是否定位
    private int locFlag = 0;//定位是否需要圈圈页面。处理SATART ,CHANGE ,FINISH都有情况，不会定位在状态改变结束时有调用反编码

    private Timer loadingTimer;//点击定位市，转圈圈动画时间控制器，
    private Timer addressTimer;//拖动地图大头针动画时间控制器

    private MyBaiduListenerHelper helper;
    private SelectAddressLocAdapter adapter;
    private SelectAddressSearchAdapter mSearchAdapter;
    private Bitmap bit;//小红点
    private String address = "";//确定的地址
    private TitleBarView mTitleBar;
    private double lat;//确定的地址纬度
    private double lng;//确定的地址经度
  //  private String mSelectProvince = "";
  //  private String mSelectCity = "";
    private String mCity = "广州市";
    private Button mBtGoRefresh;
    private TextView mTvGoSearch;
    private Button mBtLocation;
    private LocalPreferencesHelper localPreferencesHelper;
    /*
    搜索相关
     */
    private ListView mLvAddress;//搜索列表项
    private PopupWindow mPop;
    private LinearLayout mLlsearch;
    private CrossEditText mEdtSearch;
    //private LinearLayout mSearchBelow;//搜索框下面，有POPWINDOW时，透明度要改变
    private String mKeyWord;//建议查询关键字
    private LinearLayout mIvSearchLef;//左边的放大镜
    //private LinearLayout mLlCofirm;//确定按钮
    private LinearLayout ll;//头顶的提示泡

   // private LocationTansitionUtil mLocationUtil;
    private double latitude;//已有项目传进来的纬度
    private double longitude;//已有项目传进来的经度
    //private Boolean isRequesetCityProvince = false;//反编码是否请求城市和省份
    //private Boolean isRequsetSuggest=true;//编辑框改变是否请求联想

    private View mBg;
    private int mErroroCode=-1;//回调返回的错误编码
  /*  //新增地点调用
    public static void launch(Activity activity, int code){//, boolean isModify, long pid) {
        Intent intent = new Intent(activity, SelectAddressActivity.class);
       // intent.putExtra("isModify", isModify);
       // intent.putExtra("pid", pid);
        activity.startActivityForResult(intent, code);
    }*/

    //已经有地点调用
    public static void launch(Activity activity, double lat, double lng, int code) {
        Intent intent = new Intent(activity, SelectAddressActivity.class);
        intent.putExtra(LAT, lat);
        intent.putExtra(LNG, lng);
        activity.startActivityForResult(intent, code);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Log.d("===", "onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_selectaddress);

       // localPreferencesHelper = MyApplication.local;// new LocalPreferencesHelper(this, LocalPreferencesHelper.DB_NAME);
        //mLocationUtil = LocationTansitionUtil.getInstence(this);
        /*
        初始化头部
         */
        mTitleBar = (TitleBarView) findViewById(R.id.titleBar);
        mTitleBar.setCenterTitle("选择地址");
        mTitleBar.setLeftBackButtonIsVisibler(true);
        mTitleBar.setListener(TitleBarView.TitleBarEnum.ll_leftBackImageLayout, this);
        mTitleBar.setRightTextIsVisible(true, "确定");
        // mLlCofirm = (LinearLayout) mTitleBar.findViewById(R.id.right_next_text_layout);
        mTitleBar.setListener(TitleBarView.TitleBarEnum.ll_rightNextTextLayout, this);


        listLayout = (LinearLayout) findViewById(R.id.select_list);
        bar = (LinearLayout) findViewById(R.id.bar);
        mFailLoad = findViewById(R.id.fail_load);
        mBarLoad = findViewById(R.id.bar_load);
        mBtGoRefresh = (Button) findViewById(R.id.go_refresh);
        mBtGoRefresh.setOnClickListener(this);
        mTvGoSearch = (TextView) findViewById(R.id.go_search);
        mTvGoSearch.setOnClickListener(this);
        mBtLocation = (Button) findViewById(R.id.location);
        mBtLocation.setOnClickListener(this);
        anim1 = AnimationUtils.loadAnimation(this, R.anim.selectaddress_anim1);
        anim2 = AnimationUtils.loadAnimation(this, R.anim.selectaddress_anim2);
        bit = BitmapFactory.decodeResource(getResources(), R.drawable.select_address_red_circle);

        /*
         从分享足迹传过来的值
        */

        Intent intent = getIntent();
        latitude = intent.getDoubleExtra(LAT, -1);
        longitude = intent.getDoubleExtra(LNG, -1);

        //    mSearchBelow = (LinearLayout) findViewById(R.id.search_below);
        mLlsearch = (LinearLayout) findViewById(R.id.search);//搜索相关
        mIvSearchLef = (LinearLayout) findViewById(R.id.search_left_drawable);//搜索相关
        mIvSearchLef.setOnClickListener(this);
        mBg = findViewById(R.id.image_bg);
        mMaputil = new BaiduMapUtils(findViewById(R.id.bmapView), this);
        mMaputil.hiden();
        mMaputil.updateMapStatus(15);
        mMaputil.setLocaion();
        mMaputil.instanceCoder();
        mMaputil.instanceSuggestionSearch();//搜索相关


        helper = new MyBaiduListenerHelper(mMaputil);
        helper.setMapChangeListener(this);
        helper.setLocationListener(this);
        helper.setGeoListener(this);


        if (latitude == -1 || longitude == -1)
            mMaputil.startLocation();
        else {
            mMaputil.addOverlay(bit, latitude, longitude, 10);
            mMaputil.moveMap(latitude, longitude);
            mMaputil.reverseGeoCode(latitude, longitude);
        }


        /*
         搜索相关
        */
        helper.setGetSuggestionListener(this);
        LinearLayout ll = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.popupwindow_search_address_listview, null);
        mLvAddress = (ListView) ll.findViewById(R.id.search_address_list);
       // View popView=ll.findViewById(R.id.popview);
        mPop = new PopupWindow(ll, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,true);
        mPop.setOutsideTouchable(true);
        //这句是为了防止弹出菜单获取焦点之后，点击activity的其他组件没有响应
        mPop.setBackgroundDrawable(new BitmapDrawable());
      //  popView.setFocusableInTouchMode(true);
        mPop.update();
        mPop.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                mBg.setVisibility(View.GONE);
            }
        });
        mPop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        mPop.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        mEdtSearch = (CrossEditText) findViewById(R.id.edt_search);
      //  mEdtSearch.setFocusableInTouchMode(true);
        mEdtSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable arg0) {

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {

            }

            //之前注意到编辑框为空时，下面还会出现关联查询
            //导致这种情况还是编辑变化导致而成，就是如下情况：当我们编辑框为”你们“时，这时
            //回调百度函数执行关联查询，有种情况就是用户手速太快，还没回调执行完，就把编辑框置空
            //，这里置空就不执行回调。故当回调好，却是编辑框为空，还是有回调
            //可用解决方法：1,当编辑框为空时，还是执行回调。这样就不会出现回调执行完编辑框为空，还有联想的情况
            //(可能就是慢一点没有联想）
            //2，注意到当由上面情况造成时，还没回调好,用户置为空，这关键字为NULL，当执行回调，这时
            //NULL为空的，故我们可以再回调里面加这么一个判断解决上面的问题。（采用该方法）
            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2,
                                      int arg3) {
                // if(isRequsetSuggest) {
                if (cs.length() <= 0) {
                    if (mPop != null && mPop.isShowing()) {
                        mPop.dismiss();
                        // mSearchBelow.getBackground().setAlpha(255);
                        //     mSearchBelow.setBackgroundColor(getResources().getColor(R.color.white));
                        mBg.setVisibility(View.GONE);
                           /* list.setEnabled(true);
                            mBtGoRefresh.setEnabled(true);
                            mLlCofirm.setEnabled(true);*/
                        // mEdtSearch.setText(null);
                        //mEdtSearch.clearFocus();
                    }
                    mKeyWord = null;
                    return;
                }
                mKeyWord = cs.toString();
                mMaputil.requestSuggestion(cs.toString(), mCity);
                // }
                /*else
                {
                    isRequsetSuggest=true;
                }*/
            }
        });
        mEdtSearch.setOnKeyListener(new View.OnKeyListener() {//输入完后按键盘上的搜索键【回车键改为了搜索键】

            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {//修改回车键功能
                    String address = mEdtSearch.getText().toString();
                    if (!(address == null || address.equals(""))) {
                        if (mPop != null && mPop.isShowing()) {
                            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.hideSoftInputFromWindow(mEdtSearch.getWindowToken(), 0);
                            mPop.dismiss();
                            //   mSearchBelow.getBackground().setAlpha(255);
                            //   mSearchBelow.setBackgroundColor(getResources().getColor(R.color.white));
                            mBg.setVisibility(View.GONE);
                      /*  list.setEnabled(true);
                        mBtGoRefresh.setEnabled(true);
                        mLlCofirm.setEnabled(true);*/
                            mEdtSearch.clearFocus();
                        }

                        mMaputil.GeoCode(mCity, address);
                    }
                }
                return false;
            }
        });


    }


    @Override
    protected void onStart() {
        //  Log.d("===", "onstart");
        super.onStart();


    }


    @Override
    protected void onDestroy() {
        // Log.d("===", "oDestory");

        if (loadingTimer != null)
            loadingTimer.cancel();
        if (addressTimer != null)
            addressTimer.cancel();
        bit.recycle();
        mMaputil.destoryGeoCoder();
        mMaputil.stopLocation();
        mMaputil.stopLocationEnabled();
        mMaputil.destoryMapview();
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        // Log.d("===", "onResume");
        super.onResume();
        // 在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        // mMapView.onResume();
        mMaputil.onResumeMapview();
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        //mMapView.onPause();
        mMaputil.onPauseMapview();

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.left_back_layout:
                finish();
                break;
            case R.id.right_next_text_layout:
                if(mErroroCode==0) {
                 /*   if (getIntent().getBooleanExtra("isModify", false)) {

                    } else {*/
                        // String id = mLocationUtil.getIdByName(mSelectProvince + ";" + mSelectCity);
                        // String id = mLocationUtil.getIdByName(mSelectCity);
                        Intent intent = new Intent();
                        intent.putExtra(ADDRESS, address);//地址可能为“”
                        intent.putExtra(LAT, lat);
                        intent.putExtra(LNG, lng);
                        // intent.putExtra(ID, id);//id可能null
                        setResult(RESULT_OK, intent);
                        this.finish();
                   // }
                }
                else
                {
               /*     new DialogUtils(SelectAddressActivity.this, "left", true).setTitle("提示")
                            .setMessage("")
                            .setButtons(null, "确定", null).create().show();*/
                    Toast.makeText(this, "没有确定的地址", Toast.LENGTH_LONG)
                            .show();
                }
                break;
            case R.id.go_refresh:
                if (mPop != null && mPop.isShowing()) {
                    mPop.dismiss();
                    mBg.setVisibility(View.GONE);
                    //强制关闭输入法
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(mEdtSearch.getWindowToken(), 0);
                } else {
                    double centerLat = mMaputil.getCenter().latitude;
                    double cenerLng = mMaputil.getCenter().longitude;
                    mMaputil.reverseGeoCode(centerLat, cenerLng);
                }
                break;
            case R.id.go_search:
                String address = mEdtSearch.getText().toString();
                if (!(address == null || address.equals(""))) {
                    if (mPop != null && mPop.isShowing()) {
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(mEdtSearch.getWindowToken(), 0);
                        mPop.dismiss();
                        // mSearchBelow.getBackground().setAlpha(255);
                        // mSearchBelow.setBackgroundColor(getResources().getColor(R.color.white));
                        mBg.setVisibility(View.GONE);
                   /* list.setEnabled(true);
                    mBtGoRefresh.setEnabled(true);
                    mLlCofirm.setEnabled(true);*/
                        mEdtSearch.clearFocus();
                    }
                    mMaputil.GeoCode(mCity, address);
                }
                break;
            case R.id.location:
                if (mPop != null && mPop.isShowing()) {
                    mPop.dismiss();
                    mBg.setVisibility(View.GONE);
                    //强制关闭输入法
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(mEdtSearch.getWindowToken(), 0);
                } else {
                    mEdtSearch.clearFocus();
                    //isRequesetCityProvince=false;
                   // if (latitude == -1 || longitude == -1)
                        mMaputil.startLocation();
                  //  else
                 //       mMaputil.moveMap(latitude, longitude);
                }
                break;
            case R.id.search_left_drawable:
                mEdtSearch.requestFocus();
                //强制打开输入法
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(mEdtSearch, InputMethodManager.SHOW_FORCED);
                break;

        }
    }

    @Override
    public void onLocation(double lat, double lng) {
        // Log.d("===", "onlocation");
        if (mMaputil.getMapView() == null)
            return;
        isChanged = false;
        isLoc = 1;
        mMaputil.setLocationData(lat, lng, bit);
        mMaputil.animateMap(lat, lng);
        mMaputil.reverseGeoCode(lat, lng);
        mMaputil.stopLocation();

    }

    @Override
    public void onReverseGeo(int isError, final ArrayList<String> addressName,
                             final ArrayList<String> addressDistrict, final ArrayList<LatLngBean> lls, String city, final String province) {
         Log.d("===", "onRESERSEGEO"+isError);
//final ArrayList<String> addressCity

       /* if (isRequesetCityProvince) {

            isRequesetCityProvince = false;
            if (isError == 1l || isError == 2) {
                return;
            } else {
                mSelectProvince = province;
                mSelectCity = city;
            }
        } else */{
            mErroroCode=isError;//0表示没有错误，其他表示有错误
            if (isError == 1) {
                isLoc=0;
                bar.setVisibility(View.GONE);
                listLayout.setVisibility(View.GONE);
                mFailLoad.setVisibility(View.GONE);
                mBarLoad.setVisibility(View.GONE);
                Toast.makeText(this, "抱歉，未能找到结果", Toast.LENGTH_LONG)
                        .show();
                return;
            }

            if (isError == 2) {
                isLoc=0;
                listLayout.setVisibility(View.GONE);
                bar.setVisibility(View.VISIBLE);
                mFailLoad.setVisibility(View.VISIBLE);
                mBarLoad.setVisibility(View.GONE);
                return;
            }
            if (isLoc == 1) {

                isChanged = true;
                final Handler handler = new Handler(new Handler.Callback() {
                    @Override
                    public boolean handleMessage(Message msg) {
                        if (msg.what == 0x123) {
                            listLayout.setVisibility(View.VISIBLE);
                            bar.setVisibility(View.GONE);
                            mFailLoad.setVisibility(View.GONE);
                            mBarLoad.setVisibility(View.GONE);
                            //   loading.startAnimation(loadAnim);
                        }
                        return false;
                    }
                });

                listLayout.setVisibility(View.GONE);
                bar.setVisibility(View.VISIBLE);
                mFailLoad.setVisibility(View.GONE);
                mBarLoad.setVisibility(View.VISIBLE);
                loadingTimer = new Timer();
                loadingTimer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        handler.sendEmptyMessage(0x123);
                    }
                }, 300);
            } else {
                listLayout.setVisibility(View.VISIBLE);
                bar.setVisibility(View.GONE);
                mFailLoad.setVisibility(View.GONE);
                mBarLoad.setVisibility(View.GONE);
            }




            if (!city.equals(mCity)) {
                mCity = city;
                // Toast toast = Toast.makeText(SelectAddressActivity.this, "切换城市为 " + city, Toast.LENGTH_SHORT);
                // toast.show();
            }


            if (ima != null)
                mMaputil.removeView(ima);
            ima = new ImageView(this);
            ima.setBackgroundResource(R.drawable.selectaddress_search);
            poi = mMaputil.getCenterPoint();
            mMaputil.addView(ima, poi);


            if (firstLoc == 1) {
                Point poi1 = new Point();
                poi1.x = poi.x;
                poi1.y = poi.y - 80;
                ll = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.pop_selectaddress, null);

                mMaputil.addView(ll, poi1);

                firstLoc = 0;
            }


            if (isLoc == 0) {
                final Handler handler = new Handler(new Handler.Callback() {
                    @Override
                    public boolean handleMessage(Message msg) {
                        if (msg.what == 0x123) {
                            ima.startAnimation(anim2);
                        }
                        return false;
                    }
                });
                ima.startAnimation(anim1);
                addressTimer = new Timer();
                addressTimer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        handler.sendEmptyMessage(0x123);

                    }
                }, 300);

            }

            adapter = new SelectAddressLocAdapter(this, addressName, addressDistrict, 0);
            //对View中控件的操作方法
            list = (ListView) findViewById(R.id.list3);
            list.setAdapter(adapter);
            //list.setSelection(cur_pos);
            address = addressDistrict.get(0);
            lat = lls.get(0).getLatitude();
            lng = lls.get(0).getLongitude();
          //  mSelectCity = addressCity.get(0);
           // isRequesetCityProvince = true;
           // mMaputil.reverseGeoCode(lat, lng);

            //mMaputil.requestCityProvince(lat, lng);
            lastLat = lls.get(0).getLatitude();
            lastLng = lls.get(0).getLongitude();
            list.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                    if (mPop != null && mPop.isShowing()) {
                        mPop.dismiss();
                        mBg.setVisibility(View.GONE);
                        //强制关闭输入法
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(mEdtSearch.getWindowToken(), 0);
                    } else {

                        if (position == 0)
                            address = addressDistrict.get(position);
                        else
                            address = addressDistrict.get(position) + addressName.get(position);
                        isChanged = false;
                        lat = lls.get(position).getLatitude();
                        lng = lls.get(position).getLongitude();
//                        mSelectCity = addressCity.get(position);
                        //isRequesetCityProvince = true;
                       // mMaputil.reverseGeoCode(lat, lng);

                        //这里就是考虑到的当选项有地点相同时，处理情况。
                        // 注意：当有三个相同点选项时，注意不能点击相同地点项目切换不能太快，一快可能百度那边接口调用顺序就变了。
                        //有三个地点一样，然后在这三个地点间快速切换，就有问题了
                        // 考虑到项目中这种相同地点情况很少，用户三个相同地点切换速度这么快（搞破坏）导致回调变乱（如，第二次改变变量时，才执行第一次回调这种情况）
                        // （切换一次改变变量一次，本来变量改变一次就该执行完回调一次的）
                        // 比较少见，暂时不处理。
                        if (lat == lastLat && lng == lastLng) {
                            time++;
                            if (time >= 2)
                                isChanged = true;
                            isSameClick = true;
                        } else {
                            time = 0;
                            isSameClick = false;
                        }
                        lastLat = lat;
                        lastLng = lng;

                        adapter.setCurrentPos(position);
                        mMaputil.animateMap(lls.get(position).getLatitude(), lls.get(position).getLongitude());
                    }
                }
            });
            isLoc = 0;
        }
        return;
    }


    @Override
    public void mapChangeStart() {
        mEdtSearch.clearFocus();
        //   Log.d("status", "start");
        if (ll != null) {//头顶泡泡取消
            mMaputil.removeView(ll);
        }

        locFlag = 0;
        if (isLoc == 1)
            locFlag = 1;
        if (isChanged) {
            listLayout.setVisibility(View.GONE);
            bar.setVisibility(View.VISIBLE);
            mFailLoad.setVisibility(View.GONE);
            mBarLoad.setVisibility(View.VISIBLE);
        }
        if (isSameClick) {
            isChanged = true;
        }
        isSameClick = false;
    }

    @Override
    public void mapChangeFinish(LatLngBean code) {
        // Log.d("time", "mapstatufinish");
        if ((isChanged && locFlag == 0)) {//LocFlag这里一定要的，防止定位时，这里再反编码一次

            mMaputil.reverseGeoCode(code.getLatitude(), code.getLongitude());

        }
        isChanged = true;

    }

    /*
    搜索相关
     */
    @Override
    public void onGeo(Boolean isError, LatLngBean bean) {

        if (isError) {
            Toast.makeText(this, "抱歉，未能找到结果", Toast.LENGTH_LONG)
                    .show();
            return;
        }

        double latitude = bean.getLatitude();
        double longitude = bean.getLongitude();
        mMaputil.moveMap(latitude, longitude);
        mMaputil.reverseGeoCode(latitude, longitude);
    }

    @Override
    public void finish() {
        if (mPop != null && mPop.isShowing()) {
            mPop.dismiss();
            // mSearchBelow.getBackground().setAlpha(255);
            //mSearchBelow.setBackgroundColor(getResources().getColor(R.color.white));
            mBg.setVisibility(View.GONE);
            /*list.setEnabled(true);
            mBtGoRefresh.setEnabled(true);
            mLlCofirm.setEnabled(true);*/
            mEdtSearch.setText(null);
            mEdtSearch.clearFocus();
            //强制关闭输入法
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(mEdtSearch.getWindowToken(), 0);
        } else
            super.finish();
    }

    @Override
    public void onGetSuggestionResult(final ArrayList<String> addressName,
                                      ArrayList<String> addressDistrict, final ArrayList<LatLngBean> lls) {
        if ((!(addressName.size() == 0 && addressDistrict.size() == 0 && lls.size() == 0)) && mKeyWord != null) {
            //mSearchBelow.getBackground().setAlpha(0);
            //mSearchBelow.setBackgroundColor(getResources().getColor(R.color.translucent_black));

           /* list.setEnabled(false);
            mBtGoRefresh.setEnabled(false);
            mLlCofirm.setEnabled(false);*/
            mSearchAdapter = new SelectAddressSearchAdapter(this, addressName, addressDistrict, mKeyWord);
            mLvAddress.setAdapter(mSearchAdapter);
            mPop.showAsDropDown(mLlsearch, 0, 0);
            mBg.setVisibility(View.VISIBLE);
            // mPop.update();
            mLvAddress.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {

                    if (mPop != null && mPop.isShowing()) {
                        mPop.dismiss();
                        mBg.setVisibility(View.GONE);
                        //强制关闭输入法
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(mEdtSearch.getWindowToken(), 0);
                    }

                    mEdtSearch.clearFocus();
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(mEdtSearch.getWindowToken(), 0);
                    mPop.dismiss();
                    //  mSearchBelow.getBackground().setAlpha(255);
                    //  mSearchBelow.setBackgroundColor(getResources().getColor(R.color.white));
                    mBg.setVisibility(View.GONE);
                    //mEdtSearch.setText(null);
                    //   isRequsetSuggest=false;
                    //   mEdtSearch.setText(addressName.get(position));
                    mEdtSearch.clearFocus();
                   /* list.setEnabled(true);
                    mBtGoRefresh.setEnabled(true);
                    mLlCofirm.setEnabled(true);*/
                    double latitude = lls.get(position).getLatitude();
                    double longitude = lls.get(position).getLongitude();
                    mMaputil.moveMap(latitude, longitude);
                    mMaputil.reverseGeoCode(latitude, longitude);
                }
            });

        } else {
            mPop.dismiss();
            //mSearchBelow.getBackground().setAlpha(255);
            //mSearchBelow.setBackgroundColor(getResources().getColor(R.color.white));
            mBg.setVisibility(View.GONE);
            /*list.setEnabled(true);
            mBtGoRefresh.setEnabled(true);
            mLlCofirm.setEnabled(true);*/
        }
    }

    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        if (mPop != null && mPop.isShowing()) {
            mPop.dismiss();
            mBg.setVisibility(View.GONE);
            //强制关闭输入法
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(mEdtSearch.getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }


}
